package com.inbox.service;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.inbox.domain.Account;
import com.inbox.util.HibernateUtils;
import com.inbox.util.MD5Utils;

/**
 * 
 * 帐户实体类对数据库操作类
 * 
 * @author Wangpeihu
 * @since 08/01/2010
 * @version 1.0
 * 
 */
public class AccountService {

	/**
	 * 根据指定的帐户名和密码，查询是否拥有该帐户<br>
	 * 如果有，就返回该帐户，否则就返回null
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Account validateAccount(String name, String password) {
		Session session = HibernateUtils.getSession();
		String hql = "from Account where name=? and password=?";
		Query query = session.createQuery(hql);
		query.setParameter(0, name);
		/** 密码需要结果MD5摘要算法计算 */
		query.setParameter(1, MD5Utils.md5(password));
		List<Account> list = query.list();
		Account account = null;
		if (list.size() > 0) {
			account = (Account) list.get(0);
		}
		session.close();
		return account;
	}

	/**
	 * 添加一个帐户
	 * 
	 * @param account
	 */
	public void insertAccount(Account account) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {

			/** 密码需要结果MD5摘要算法计算 */
			account.setPassword(MD5Utils.md5(account.getPassword()));

			session.save(account);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	@Test
	public void testInsertAccount() {
		Account account = new Account();
		account.setName("110");
		account.setPassword("110");
		insertAccount(account);
	}

	public static void main(String[] args) {
		AccountService a = new AccountService();
		a.testInsertAccount();
	}
}
